package com.xms.webresource.api.controller;

import com.xms.core.exception.XmsException;
import com.xms.core.model.KeyValuePair;
import com.xms.utils.StringUtil;
import com.xms.utils.UUIDUtil;
import com.xms.web.framework.controller.ApiBaseController;
import com.xms.web.framework.model.JsonResultObject;
import com.xms.webresource.api.model.CreateWebResourceModel;
import com.xms.webresource.entity.WebResource;
import com.xms.webresource.service.IWebResourceContentCoder;
import com.xms.webresource.service.IWebResourceCreaterService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.time.LocalDate;

/**
 * <p>
 * WebResourceCreaterController
 * </p>
 *
 * @author migo
 * @since 2021/9/19
 */
@RestController
@RequestMapping("{org}/api/webresource")
public class WebResourceCreaterController extends ApiBaseController {
    private IWebResourceCreaterService _webResourceCreaterService;
    private IWebResourceContentCoder _webResourceContentCoder;
    @Autowired
    public WebResourceCreaterController(IWebResourceCreaterService webResourceCreaterService,
                                        IWebResourceContentCoder webResourceContentCoder)
    {
        _webResourceCreaterService = webResourceCreaterService;
        _webResourceContentCoder = webResourceContentCoder;
    }

    @ApiOperation("新建Web资源")
    @PostMapping("create")
    public JsonResultObject create(@RequestBody CreateWebResourceModel model) throws UnsupportedEncodingException, XmsException, SQLException {
        if(StringUtil.isEmpty(model.name) || StringUtil.isEmpty(model.content)){
            return JNotSpecifiedParams("name", "content");
        }
        WebResource entity = new WebResource();
        entity.setWebresourceid(UUIDUtil.get());
        entity.setWebresourcetype(model.webresourcetype);
        entity.setName(model.name);
        entity.setContent(_webResourceContentCoder.encode(model.content));
        entity.setDescription(model.description);
        entity.setOrganizationid(_currentUser.getUser().OrganizationId);
        entity.setCreatedby(_currentUser.getUser().SystemUserId);
        entity.setCreatedon(LocalDate.now());
        return _webResourceCreaterService.create(entity) ?
                JCreateSuccess(KeyValuePair.build("id", entity.getWebresourceid())) : JCreateFailure();
    }
}
